﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using JXT.PrimaryKey.Batman.Cache;
using JXT.PrimaryKey.Batman.Core.Cache;
using JXT.PrimaryKey.Batman.Domain.Services;
using JXT.PrimaryKey.Batman.Domain.Quotation.Models;
using JXT.PrimaryKey.Batman.Domain.Quotation.Repositories;
using JXT.PrimaryKey.Batman.Domain.Specifications;

namespace JXT.PrimaryKey.Batman.Domain.Quotation.Services.Default
{
    public class SecuritiesBindingService : CachedServiceBase<SecuritiesBinding>, ISecuritiesBindingService
    {
        private static readonly string _cacheKey = String.Format("{0}_list", CacheSpace);
        private ICache _httpCache = new HttpCache();

        #region ISecuritiesBindingService Members

        public void Save(SecuritiesBinding entity)
        {
            if (entity == null)
                throw new ArgumentNullException("entity");
            if (entity.Id > 0)
                LoadRepository<ISecuritiesBindingRepository>().Update(entity);
            else
                LoadRepository<ISecuritiesBindingRepository>().Add(entity);
            ClearCache();
        }

        public SecuritiesBinding GetSingle(string code, MarketType type)
        {
            if (String.IsNullOrWhiteSpace(code))
                throw new ArgumentNullException("code");
            //var specification = SpecificationFactory.CreateSpecification<SecuritiesBinding>();
            //specification.And(e => e.Code == code && e.MarketType == type);
            //return GetSingle(specification);
            return GetList().FirstOrDefault(e => e.Code == code && e.MarketType == type);
        }

        public IEnumerable<SecuritiesBinding> GetList()
        {
            var list = _httpCache.Get(_cacheKey) as IList<SecuritiesBinding>;
            if (list == null)
            {
                list = LoadRepository<ISecuritiesBindingRepository>().GetList().ToList();
                _httpCache.Add(_cacheKey, list);
            }
            return list;
        }

        #endregion

        public override void ClearCache()
        {
            base.ClearCache();
            _httpCache.Remove(_cacheKey);
        }
    }
}
